//
//  MessageMapViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/30.
//  Copyright © 2015年 Fine. All rights reserved.
//

#import "MessageMapViewController.h"
//#import <AMapLocationKit/AMapLocationManager.h>
#import <CoreLocation/CoreLocation.h>
@interface MessageMapViewController () <MAMapViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *mapParentView;
@property (weak, nonatomic) IBOutlet UILabel *location;
@property (weak, nonatomic) IBOutlet UILabel *event;
@property (weak, nonatomic) IBOutlet UILabel *xueyangNum;
@property (weak, nonatomic) IBOutlet UILabel *xueyangAbout;
@property (weak, nonatomic) IBOutlet UILabel *xinlvNum;
@property (weak, nonatomic) IBOutlet UILabel *xinlvAbout;
@property (weak, nonatomic) IBOutlet UITextView *advice;
@property (strong, nonatomic) UIButton *testBtn;
@property (strong, nonatomic) MAMapView *mapView;
//@property (strong, nonatomic) AMapLocationManager *manager;
@property (strong, nonatomic) CLGeocoder *geo;

@end
//requestLocationWithReGeocode
@implementation MessageMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([_model.type integerValue] == 1) {
        self.title = @"紧急呼救";
    } else if ([_model.type integerValue] == 2) {
        self.title = @"健康报警";
    } else if ([_model.type integerValue] == 3) {
        self.title = @"健康预警";
    } else if ([_model.type integerValue] == 4) {
        self.title = @"跌倒报警";
    }
   
    
    [self showNavBarWithRightTitle:nil
                    andRightAction:nil
                     andLeftAction:nil
                 andRightBtnIsShow:NO];
    [self initAlsoSetCoordinate];
}


- (void)initAlsoSetCoordinate {
    [self setUpMapView];
    CLLocationCoordinate2D coordina;
    _warningTitle.text = [self.title stringByAppendingString:@"位置"];
    if (![_model.latitude doubleValue] == 0.0 && ![_model.longitude doubleValue] == 0.f) {
        coordina = CLLocationCoordinate2DMake([_model.latitude doubleValue], [_model.longitude doubleValue]);
        MyAnnotation *annotation = [[MyAnnotation alloc] initWithCoordinates:coordina title:@"watchCoor" subTitle:@"" identifer:@"watch"];
        [_mapView addAnnotation:annotation];
    } else {
        [SVProgressHUD showErrorWithStatus:@"无法获取报警位置！"];
    }
    if (_geo == nil) {
        _geo = [[CLGeocoder alloc] init];
    }
    [_geo reverseGeocodeLocation:[[CLLocation alloc] initWithLatitude:coordina.latitude longitude:coordina.longitude] completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error && placemarks.count == 0) {
            
        } else {
            CLPlacemark *place =  [placemarks firstObject];
            _location.text = [place.locality stringByAppendingString:place.name];
        }
    }];
    _event.text = [NSString stringWithFormat:@"您于%@年%@月%@日进行了%@",_model.year,_model.month,_model.day,self.title];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (_mapView) {
        _mapView.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_mapView.delegate != nil) {
        _mapView.delegate = nil;
    }
}


- (void)setUpMapView {
    if (_mapView==nil) {
        _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0,
                                                               0,
                                                               CGRectGetWidth(_mapParentView.bounds),
                                                               CGRectGetHeight(_mapParentView.bounds))];
        _mapView.delegate = self;
        _mapView.showsUserLocation = YES;
        _mapView.userTrackingMode = MAUserTrackingModeNone;
//        [_mapView setZoomLevel:16.1 animated:YES];
        [_mapParentView addSubview:_mapView];
    } else {
        _mapView.showsUserLocation = YES;
    }
}

-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation
updatingLocation:(BOOL)updatingLocation
{
    if(updatingLocation)
    {
        [self convertCenterCoordinate2D:CLLocationCoordinate2DMake([_model.latitude doubleValue], [_model.longitude doubleValue]) lastCoor:userLocation.coordinate];       
    }
}

- (MAAnnotationView*)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    MAAnnotationView * result = nil;
    if([annotation isKindOfClass:[MyAnnotation class]])
    {
        return  [self mapViewWithAnnotationView:annotation];
    }
    static NSString *annotationStr = @"MAPinAnnotationView";
    MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:annotationStr];
    if (annotationView == nil) {
        annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationStr];
        [annotationView setCanShowCallout:YES];
    }
    annotationView.opaque = NO;
    annotationView.animatesDrop = YES;
    annotationView.draggable = YES;
    annotationView.selected = YES;
    annotationView.calloutOffset = CGPointMake(15, 15);
    annotationView.image = [UIImage imageNamed:@"detail_p"];
    result = annotationView;
    return result;
}

- (MAAnnotationView *)mapViewWithAnnotationView:(id<MAAnnotation>)annotation {
     MAAnnotationView * result = nil;
    MyAnnotation * senderAnnotation = (MyAnnotation *)annotation;
    MAPinAnnotationView * annotationView = (MAPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:senderAnnotation.identifier];
    if(annotationView == nil)
    {
        annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:senderAnnotation reuseIdentifier:senderAnnotation.identifier];
        
        [annotationView setCanShowCallout:YES];
    }
    annotationView.opaque = NO;
    annotationView.animatesDrop = YES;
    annotationView.draggable = YES;
    annotationView.selected = YES;
    annotationView.calloutOffset = CGPointMake(15, 15);
    annotationView.image = [UIImage imageNamed:@"detail_p2"];
    result = annotationView;
    return result;
}

//传两个坐标求出中心点并转换为地图的坐标
- (void)convertCenterCoordinate2D:(CLLocationCoordinate2D)firstCoor lastCoor:(CLLocationCoordinate2D)lastCoor {
    //取出当前位置的坐标
    CGPoint phonePoint = [_mapView convertCoordinate:firstCoor toPointToView:self.view];
    CGPoint watchPoint = [_mapView convertCoordinate:lastCoor toPointToView:self.view];
    CGPoint centerPoint = CGPointMake(fabs(phonePoint.x - watchPoint.x) / 2 + fmin(phonePoint.x, watchPoint.x), fabs(phonePoint.y - watchPoint.y) / 2 + fmin(phonePoint.y, watchPoint.y));
    CLLocationCoordinate2D centerCoor = [_mapView convertPoint:centerPoint toCoordinateFromView:self.view];
    [_mapView setCenterCoordinate:centerCoor];
    
    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    for(id<MAAnnotation> annotation in _mapView.annotations) {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }
    MACoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.5;
    
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5;
    
    region = [_mapView regionThatFits:region];
    [_mapView setRegion:region animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
